package cn.lzm.basic.service.impl;

import cn.lzm.basic.config.BussinessException;
import cn.lzm.basic.constant.BaseConstant;
import cn.lzm.basic.dto.EmailCodeDto;
import cn.lzm.basic.service.IRegisterService;
import cn.lzm.basic.util.MD5Utils;
import cn.lzm.basic.util.StrUtils;
import cn.lzm.user.domain.Logininfo;
import cn.lzm.user.domain.User;
import cn.lzm.user.dto.EmailRegisterDto;
import cn.lzm.user.dto.PhoneRegisterDto;
import cn.lzm.user.mapper.LogininfoMapper;
import cn.lzm.user.mapper.UserMapper;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class RegisterServiceImpl implements IRegisterService {
//    @Autowired
//    private RegisterMapper registerMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Override
    public void phoneRegister(PhoneRegisterDto dto) {
        this.verification(dto);
        User user = dtoConvertUser(dto);
        Logininfo logininfo = userConverLogininfo(user);
        // 添加
        logininfoMapper.add(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);

    }



    private Logininfo userConverLogininfo(User user){
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        return logininfo;
    }
    private User dtoConvertUser(PhoneRegisterDto dto){
        // 盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 密码加密
        String password = salt + dto.getPassword();
        String encrypPwd = MD5Utils.encrypByMd5(password);
        return User
                .builder()
                .username(dto.getPhone())
                .phone(dto.getPhone())
                .salt(salt)
                .password(encrypPwd)
                .state(1)
                .createtime(new Date())
                .build();
    }

    private Logininfo userConverLogininfo1(User user){
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        return logininfo;
    }
    private User dtoConvertUser1(EmailRegisterDto dto){
        // 盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 密码加密
        String password = salt + dto.getPassword();
        String encrypPwd = MD5Utils.encrypByMd5(password);
        return User
                .builder()
                .username(dto.getEmail())
                .email(dto.getEmail())
                .salt(salt)
                .password(encrypPwd)
                .state(1)
                .createtime(new Date())
                .build();
    }

    private void verification(PhoneRegisterDto dto) {
        // 非空判断
        // 验证两次密码是否一致
        if (!dto.getPassword().equals(dto.getPasswordRepeat())){
            throw new BussinessException("密码不一致");
        }
        // 判断验证是否超时
        //判断短信验证码是否已值
        // 【redis中 key：register:smscode:phone  value：验证码:时间戳】

        String redisSmsCode = (String)redisTemplate.opsForValue().get(String.format(BaseConstant.VerfityCodeCons.REGISTER_SMSCODE_PHONE, dto.getPhone()));
        String[] split = redisSmsCode.split(":");
        if (StringUtils.isBlank(redisSmsCode)) {
            throw new BussinessException("验证码错误！");
        }
        String[] smsCode = redisSmsCode.split(":");
        if (!smsCode[0].equals(dto.getSmsCode())) {
            throw new BussinessException("验证码错误！");
        }
        // 当前手机号是否已经注册了
        User user = userMapper.findByPhone(dto.getPhone());
        if (null != user){
            throw new BussinessException("滚去登陆！");
        }
    }

    @Override
    public void emailRegister(EmailRegisterDto dto) {
        verificationEmail(dto);
        User user = dtoConvertUser1(dto);
        Logininfo logininfo = userConverLogininfo1(user);
        // 添加
        logininfoMapper.add(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
    }

    private void verificationEmail(EmailRegisterDto dto) {
        // 非空判断
        // 验证两次密码是否一致
        if (!dto.getPassword().equals(dto.getPasswordRepeat())){
            throw new BussinessException("密码不一致");
        }
        // 判断验证是否超时
        //判断短信验证码是否已值
        // 【redis中 key：register:smscode:phone  value：验证码:时间戳】

        String redisEmailCode = (String)redisTemplate.opsForValue().get(String.format(BaseConstant.VerfityCodeCons.REGISTER_EMAIL, dto.getEmail()));
        String[] split = redisEmailCode.split(":");
        if (StringUtils.isBlank(redisEmailCode)) {
            throw new BussinessException("验证码错误！");
        }
        String[] smsCode = redisEmailCode.split(":");
        if (!smsCode[0].equals(dto.getEmailCode())) {
            throw new BussinessException("验证码错误！");
        }

        // 当前手机号是否已经注册了
        User user = userMapper.findByEmail(dto.getEmail());
        if (null != user){
            throw new BussinessException("邮箱已被注册！");
        }
    }
}
